const express = require("express")
const {con,getMysql} = require('../mysql/mysql.js'); 
 const Mail=require("../mysql/mail.js")
const login = express.Router() //创建路由

let codes={
  code:null
}
//发送验证码部分
login.get('/postmail',async (req,res)=>{
  let {email}=req.query
  let code1=parseInt(Math.random()*10000)
  let data1=await Mail.sendmail(email,code1)
  codes.code=code1
  res.send({status:200,message:"ok"})
})


//注册
login.post("/register",async (req,res)=>{
  let {username,password,yzm,author}=req.body
  let str="select * from user where username=?||author=?"
  let data=await getMysql(str,[username,author])
  if(codes.code==yzm){
    if(data.length!=0){
      res.send({data:"已经存在了",num:1})
      return 
    }
    let str1="insert into user (username,password,author) values (?,?,?)"
    let data1=await getMysql(str1,[username,password,author])
    res.send({data:"注册成功",num:2})
  }
  res.send({status:404,data:"验证码错误",num:3})
})


//登录
login.get("/login",async (req, res) => {  //必须要先匹配到/login ，才能来这儿
  let {username,password}=req.query
    let str="select * from user where username=? and password=?"
    let data=await getMysql(str,[username,password])
    if(data.length==0){
      res.send({status:404,message:"登录失败"})
    }
    req.session.username=username
    res.send({status:200,message:"登录成功",cookie:123456,data:data})
})

module.exports = login
